package com.library.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.bean.Book;
import com.library.service.BookService;
import com.library.service.impl.BookServiceImpl;


@WebServlet("/bookServlet.do")
public class BookServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String opt = request.getParameter("opt");
		switch(opt) {
			case "0":
				delete(request,response);
				break;
			case "1":
				add(request,response);
				break;
		}
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
	
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		BookService bs = new BookServiceImpl();
		int bookId = Integer.parseInt(request.getParameter("bookId"));
		bs.deleteBook(bookId);
		response.sendRedirect("success.jsp");
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		BookService bs = new BookServiceImpl();
		String bookName = request.getParameter("bookName");
		String bookWriter = request.getParameter("bookWriter");
		int bookNum = 0;
		try {
			bookNum = Integer.parseInt(request.getParameter("bookNum"));
		}catch(Exception e) {
			request.setAttribute("msg", "书本数目应该为数字");
			request.getRequestDispatcher("addBook.jsp").forward(request, response);
		}
		bs.addBook(new Book(bookName,bookWriter,bookNum));
		response.sendRedirect("addBook.jsp");
	}
}
